package com.iretailer.report.web.business;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iretailer.report.base.BaseAction;
import com.iretailer.report.common.InternationalMessage;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.dto.ReMalls;
import com.iretailer.report.model.*;
import com.iretailer.report.util.RMap;
import com.iretailer.report.util.SecurityUserUtil;
import com.iretailer.report.util.StringUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xjw
 * @Date: 2019/1/25 13:40
 * @Description:
 */
@RestController
public class MallController extends BaseAction {

    @RequestMapping("/business/selectCompanyMall.action")
    public Map<String, Object> selectCompanyMall(@RequestBody(required = false) ReMalls reMalls,HttpServletRequest request) {
         User user = SecurityUserUtil.currentUser(request);
        LambdaQueryWrapper<Malls> queryWrapper = new QueryWrapper<Malls>().lambda();
        if (reMalls != null && StringUtil.notEmpty(reMalls.getCompanyId())) {
            // 如果传入一个 CompanyId 就按CompanyId 查询
            queryWrapper.eq(Malls::getCompanyId, reMalls.getCompanyId());
        } else {
            // 如果 不上 admin 权限
            if (!"-".equals(user.getRoleId())) {
//                List<String> companies = companyService.getTreeId(user.getCompanyId());
//                companies.add(user.getCompanyId());
//                queryWrapper.in(Malls::getCompanyId, companies);

//                List<Malls> mallsList = mallsService.selectMallsByUserId_enabled(user.getId(), 1);
//                return RMap.ok(mallsList);
                List<String> mallIds = userMallService.selectUserMallIds(user.getId());
                queryWrapper.in(Malls::getId, mallIds);
            }
        }
        List<Malls> mallsList = mallsService.list(queryWrapper.eq(Malls::getEnabled, 1));
        return RMap.ok(mallsList);
    }

    @RequestMapping("/business/userMall.action")
    public Map<String, Object> userMall(@RequestBody ReMalls reMalls) {
        List<Malls> userMalls = mallsService.selectMallsByUserId_enabled(reMalls.getUserId(), null);
        return RMap.ok(userMalls);
    }

    @RequestMapping("/business/sendRegularlyMall.action")
    public Map<String, Object> sendRegularlyMall(@RequestBody ReMalls reMalls) {
        List<Malls> malls = mallsService.sendMallBySendregularyId_enabled(reMalls.getSendregularyId(), null);
        return RMap.ok(malls);
    }


    @RequestMapping("/business/businessTimeMall.action")
    public Map<String, Object> businessTimeMall(@RequestBody ReMalls reMalls) {
        List<Malls> userMalls = mallsService.selectMallsByBusinesstimeId_enabled(reMalls.getBusinessTimeId(), null);
        return RMap.ok(userMalls);
    }

    @RequestMapping("/business/coefficientMall.action")
    public Map<String, Object> coefficientMall(@RequestBody ReMalls reMalls) {
        List<Malls> userMalls = mallsService.selectMallsByCoefficientId_enabled(reMalls.getCoefficientId(), null);
        return RMap.ok(userMalls);
    }


    @RequestMapping("/business/tagTypeMall.action")
    public Map<String, Object> tagTypeMall(@RequestBody ReMalls reMalls) {
        List<Malls> malls = mallsService.selectMallsByTagTypeId_enabled(reMalls.getTagTypeId(), null);
        return RMap.ok(malls);
    }

    @RequestMapping("/business/gridMall.action")

    public Map<String, Object> grid(@RequestBody ReMalls reMalls, HttpServletRequest request) {
        User user = SecurityUserUtil.currentUser(request);
        QueryOption queryOption = modelMapper.map(reMalls, QueryOption.class);
        String userId = user.getId();
        if ("-".equals(user.getRoleId())) {
            userId = null;
        }
        PageResult<Malls> result = mallsService.grid(userId, reMalls.getEnabled(), reMalls.getCompanyName(), reMalls.getName(), reMalls.getMallCode(), reMalls.getTimeZone(), queryOption);

        return RMap.ok(result);

    }


    @RequestMapping("/business/saveOrUpdateMall.action")
    public Map<String, Object> saveOrUpdateMall(@RequestBody ReMalls reMalls,HttpServletRequest request) {
         User user = SecurityUserUtil.currentUser(request);
        Malls malls = modelMapper.map(reMalls, Malls.class);

        Malls findMalls = mallsService.getOne(new QueryWrapper<Malls>().lambda().eq(Malls::getName, malls.getName()));
        if (findMalls != null) {
            // 如果插入数据
            if (StringUtil.empty(malls.getId())) {
                return RMap.error(RMap.Code.DATAREPETITION, "mallname_already_exists");
            } else {
                if (!findMalls.getId().equals(malls.getId())) {
                    return RMap.error(RMap.Code.DATAREPETITION, "mallname_already_exists");
                }
            }
        }
        boolean result = mallsService.saveOrUpdate(malls, user);
        return RMap.resultBoolean(result);
    }

    @RequestMapping("/business/mallExistDevices")
    public Map<String, Object> mallExistDevices(@RequestBody List<String> ids,HttpServletRequest request) {
//        Malls m = new Malls();
//        m.setDeleteFlag(-1);
//        m.setEnabled(-1);
//        boolean result = mallsService.update(m, new QueryWrapper<Malls>().lambda().in(Malls::getId, ids));
        for (String id : ids) {
            if (devicesService.count(new QueryWrapper<Device>().lambda().eq(Device::getMallId, id)) > 0 ||
                    cameraService.count(new QueryWrapper<Camera>().lambda().eq(Camera::getMallId, id)) > 0) {
                return RMap.error(String.format("%s 【%s】",
                        InternationalMessage.MALL_EXISTS_DEVICES.getByLanguage(SecurityUserUtil.userLanguage(request)),
                        mallsService.getById(id).getName()));
            }
        }
        return RMap.ok(true);
    }

    @RequestMapping("/business/delMall.action")
    @Transactional
    public Map<String, Object> del(@RequestBody List<String> ids) {
//        Malls m = new Malls();
//        m.setDeleteFlag(-1);
//        m.setEnabled(-1);
//        boolean result = mallsService.update(m, new QueryWrapper<Malls>().lambda().in(Malls::getId, ids));
        return RMap.resultBoolean(mallsService.removeByIds(ids) &&
                cameraService.remove(new QueryWrapper<Camera>().lambda().in(Camera::getMallId, ids)) &&
                devicesService.remove(new QueryWrapper<Device>().lambda().in(Device::getMallId, ids))
        );
    }

    @RequestMapping("/business/selectCompanyMallByMallid.action")
    public Map<String, Object> selectCompanyMallByMallid(@RequestBody ReMalls reMalls) {
        if (StringUtil.notEmpty(reMalls.getId())) {
            CompanyMalls companyMalls = mallsService.selectCompanyMalls(new QueryWrapper<CompanyMalls>().eq("Id", reMalls.getId()));
            return RMap.ok(companyMalls);
        } else {
            return RMap.error();
        }
    }

    @RequestMapping("/business/selectMallByCompanyId.action")
    public Map<String, Object> selectMallByCompanyId(@RequestBody ReMalls reMalls) {
        if (StringUtil.notEmpty(reMalls.getCompanyId())) {
            List<Malls> malls = mallsService.list(new QueryWrapper<Malls>().lambda().eq(Malls::getCompanyId, reMalls.getCompanyId()));
            return RMap.ok(malls);
        } else {
            return RMap.error();
        }
    }
}
